<script setup>
import {onMounted, reactive, ref} from "vue"
import axios from "axios"
import {Plus, Search} from "@element-plus/icons-vue"
import {ElMessage, ElMessageBox} from "element-plus"
import {useRoute} from "vue-router";

// 响应式数据优化
const url = 'http://localhost:8080/file/downLoad?fileName='
const saveOrUpdateVisible = ref(false)
const saveOrUpdateTitle = ref('')
const userNames = ref([])
const questionNames = ref([])
const Id = JSON.parse(localStorage.getItem('userInfo')).id
const formLabelWidth = '140px' // 补充样式变量
const route = useRoute()
// 表单数据保持响应性
const replyForm = reactive({
  id: '',
  replyText: '',
  userId: Id,
  questionId: '',
  parentReplyId: '',
  createTime: '',
})

// 分页数据
const total = ref(0)
const formInline = reactive({
  pageNum: 1,
  pageSize: 5,
  replyText: '',
  questionId: '',
})

// 表单验证规则
const formRules = reactive({
  replyText: [{required: true, message: '回复内容不能为空', trigger: 'blur'}],
  questionId: [{required: true, message: '请选择问题', trigger: 'change'}],
  userId: [{required: true, message: '请选择用户', trigger: 'change'}]
})

// 生命周期钩子
onMounted(() => {
  if (route.query.questionId) {
    const questionId = Number(route.query.questionId)
    formInline.questionId = questionId
    replyForm.questionId = questionId
  }
  getList()
  fetchUsers()// 获取用户列表
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    const res = await axios.get('/user/selectAll')
    userNames.value = res.data.data
  } catch (error) {
    ElMessage.error('用户列表获取失败')
  }
}

// 获取问题列表（带错误处理）
const selectQuestionByUserId = async (userId) => {
  try {
    const res = await axios.get(`/question/selectByUserId/${userId}`)
    questionNames.value = res.data.data
  } catch (error) {
    ElMessage.error('问题列表获取失败')
  }
}

// 核心数据获取（优化并行请求）
const getList = async () => {
  try {
    const res = await axios.post('/reply/select', formInline)
    total.value = res.data.data.total
    const list = res.data.data.list
    tableData.value = await Promise.all(
        list.map(async item => {
          try {
            // 获取问题详情
            const questionRes = await axios.get(`/question/selectById/${item.questionId}`)
            const userRes = await axios.get('/user/selectById', {params: {id: questionRes.data.data?.userId}})
            return {
              ...item,
              questionName: questionRes.data.data?.title || '未知问题',
              userName: userRes.data?.name || '未知用户'
            }
          } catch (error) {
            console.error('关联数据获取失败:', error)
            return {
              ...item,
              questionName: '未知问题',
              userName: '未知用户'
            }
          }
        })
    )
  } catch (error) {
    ElMessage.error('数据获取失败')
  }
}
// 表单提交（带验证）
const formRef = ref()
const saveOrUpdate = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    const apiMethod = saveOrUpdateTitle.value === '编辑'
        ? await axios.post('/reply/update', replyForm)
        : await axios.post('/reply/insert', replyForm)

    const res = await apiMethod
    if (res.data.code === 1) {
      ElMessage.success(saveOrUpdateTitle.value + '成功')
      saveOrUpdateVisible.value = false
      await getList()
    } else {
      throw new Error(res.data.msg || '操作失败')
    }
  } catch (error) {
    if (error.name !== 'Error') {
      ElMessage.warning('请完善表单')
    } else {
      ElMessage.error(error.message)
    }
  }
}

// 删除操作（优化错误处理）
const onDel = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await axios.delete(`/reply/delete/${id}`)
    if (res.data.code === 1) {
      ElMessage.success('删除成功')
      await getList()
    } else {
      throw new Error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message)
    }
  }
}

// 编辑操作（保持响应性）
const onEdit = (row) => {
  Object.assign(replyForm, row)
  selectQuestionByUserId(row.userId)
  saveOrUpdateTitle.value = '编辑'
  saveOrUpdateVisible.value = true
}

// 新增操作（重置表单）
const onAdd = () => {
  Object.assign(replyForm, {
    id: '',
    replyText: '',
    userId: Id,
    questionId: '',
    parentReplyId: '',
    createTime: '',
  })
  saveOrUpdateTitle.value = '新增'
  saveOrUpdateVisible.value = true
}

// 分页处理
const handleSizeChange = (val) => {
  formInline.pageSize = val
  formInline.pageNum = 1
  getList()
}

const handleCurrentChange = (val) => {
  formInline.pageNum = val
  getList()
}

const tableData = ref([])
</script>

<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="formInline" class="search-form">
      <el-form-item label="回复内容">
        <el-input
            v-model="formInline.replyText"
            placeholder="请输入内容"
            clearable
            @keyup.enter="getList"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="success" :icon="Search" @click="getList">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="toolbar">
      <el-button type="primary" :icon="Plus" @click="onAdd">新增</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="replyText" label="内容" min-width="200" show-overflow-tooltip/>
      <el-table-column prop="createTime" label="时间" width="180"/>
      <el-table-column prop="questionName" label="问题" width="180"/>
      <el-table-column prop="userName" label="用户" width="120"/>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="onEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="onDel(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="formInline.pageNum"
        v-model:page-size="formInline.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 表单弹窗 -->
    <el-dialog
        v-model="saveOrUpdateVisible"
        :title="saveOrUpdateTitle"
        width="500px"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :model="replyForm"
          :rules="formRules"
          label-position="right"
          :label-width="formLabelWidth"
      >
        <el-form-item label="用户" prop="userId">
          <el-select
              v-model="replyForm.v_id"
              placeholder="请选择用户"
              @change="selectQuestionByUserId"
          >
            <el-option
                v-for="user in userNames"
                :key="user.id"
                :label="user.name"
                :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联问题" prop="questionId">
          <el-select v-model="replyForm.questionId" placeholder="请选择问题">
            <el-option
                v-for="question in questionNames"
                :key="question.id"
                :label="question.title"
                :value="question.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="回复内容" prop="replyText">
          <el-input
              v-model="replyForm.replyText"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveOrUpdateVisible = false">取消</el-button>
          <el-button type="primary" @click="saveOrUpdate">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 优化表格样式 */
.el-table {
  margin-top: 10px;
}

/* 调整表单标签对齐 */
:deep(.el-form-item__label) {
  padding-right: 12px;
}

/* 优化弹窗按钮位置 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>